package com.ruoyi.womp.task;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import com.ruoyi.womp.service.ISqlQueryService;

@Component("hisDataMonthTask")
public class HisDataMonthTask {

	final static String TASK_NAME = "历史数据处理任务(月)";

	@Autowired
	MongoTemplate mongoTemplate;

	@Autowired
	ISqlQueryService sqlQueryService;

	public void execute() {
		handleData();
	}

	private void handleData() {
		try {

			// 月数通过参数设置中设置
			String sql = "select config_value from sys_config where config_key='realtime_data_save_month'";
			Integer months = sqlQueryService.getInteger(sql);

			// 所有集合名称
			Set<String> collectionNameSet = mongoTemplate.getCollectionNames();

			for (String name : collectionNameSet) {
				// WRD开头、第三部分长度7、长三部分以S开头
				String[] nameParts = name.split("_");
				if (nameParts.length == 3 && nameParts[0].equals("WRD") && nameParts[2].length() == 7
						&& nameParts[2].startsWith("S")) {
					// 取名称中的年月与当前年月相比，小于设置月数的删除
					String yearMonth = nameParts[2].substring(1);

					LocalDate startDate = LocalDate.of(Integer.parseInt(yearMonth.substring(0, 4)),
							Integer.parseInt(yearMonth.substring(4)), 1);
					LocalDate endDate = LocalDate.of(Calendar.getInstance().get(Calendar.YEAR),
							Calendar.getInstance().get(Calendar.MONTH) + 1, 1);

					long diffMonth = ChronoUnit.MONTHS.between(startDate, endDate);

					if (diffMonth > months) {
						mongoTemplate.dropCollection(name);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}